package pers.gxm.flyweight;

public class BigString {
    private static BigString[] bsArray = new BigString[1000];
    public static void main(String[] args) {
        System.out.println("共享big字符时");
        testAllocation(true);
        System.out.println("不共享big字符时");
        testAllocation(false);
    }

    private BigChar[] bigChars;



    public BigString(String string){
        this(string,true);
    }
    public BigString(String string,boolean shared){
        /**
         * 怎么根据布尔值调用不同的构造器，难点在于调用自身的其它构造器必须放在第一行
         */
        bigChars = new BigChar[string.length()];
        if(shared){
            sharedBigChar(string);
        }else {
            notSharedBigChar(string);
        }
    }

    private void sharedBigChar(String string){
        BigCharFactory bigCharFactory = BigCharFactory.getInstance();
        for(int i = 0;i < string.length();i++){
            bigChars[i] =  bigCharFactory.getBigChar(string.charAt(i));
        }
    }
    private void notSharedBigChar(String string){
        for(int i = 0;i < string.length();i++){
            bigChars[i] =  new BigChar(string.charAt(i));
        }
    }
    public void print(){
        for(int i = 0;i < bigChars.length;i++){
            bigChars[i].print();
        }
    }

    public static void testAllocation(boolean shared){
        for (int i = 0;i < bsArray.length;i++){
            bsArray[i] = new BigString("1212123",shared);
        }
        usedMemory();
    }

    public static void usedMemory(){
        Runtime.getRuntime().gc();
        long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        System.out.println("使用内存 = " + used);

    }
}
